package gw.com.android.ui.chart.manager;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

import com.gwtsz.chart.charts.Chart;
import com.gwtsz.chart.components.Legend;
import com.gwtsz.chart.components.XAxis;
import com.gwtsz.chart.components.YAxis;
import com.gwtsz.chart.data.CandleData;
import com.gwtsz.chart.data.CandleDataSet;
import com.gwtsz.chart.data.CandleEntry;
import com.gwtsz.chart.data.CombinedData;
import com.gwtsz.chart.data.Entry;
import com.gwtsz.chart.data.LineData;
import com.gwtsz.chart.data.LineDataSet;
import com.gwtsz.chart.data.StickData;
import com.gwtsz.chart.formatter.YAxisValueFormatter;
import com.gwtsz.chart.highlight.Highlight;
import com.gwtsz.chart.interfaces.datasets.ILineDataSet;
import com.gwtsz.chart.listener.OnChartValueSelectedListener;
import com.gwtsz.chart.output.bean.DataParse;
import com.gwtsz.chart.output.bean.KLineBean;
import com.gwtsz.chart.output.customer.CoupleChartGestureListener;
import com.gwtsz.chart.output.customer.GWYAxisRenderer;
import com.gwtsz.chart.output.customer.MyBottomMarkerView;
import com.gwtsz.chart.output.customer.MyCombinedChart;
import com.gwtsz.chart.output.customer.MyRightMarkerView;
import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.chart.output.utils.ChartRendererFactory;
import com.gwtsz.chart.output.utils.ChartThemeUtil;
import com.gwtsz.chart.output.utils.GTTIndicatorsModel;
import com.gwtsz.chart.output.utils.GTTLineModel;
import com.gwtsz.chart.output.utils.Periodicity;
import com.gwtsz.chart.renderer.YAxisRenderer;
import com.gwtsz.chart.utils.Utils;
import com.gwtsz.chart.utils.ViewPortHandler;
import com.gwtsz.gts2.hx.R;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import gw.com.android.app.GTConfig;
import www.com.library.app.Logger;
import www.com.library.util.StringFormatter;

/**
 * Created by spence on 17-3-16.
 */

public class CandleControl implements ChartInterface {

  private static String TAG=CandleControl.class.getSimpleName();

  private static String METHOD="class="+TAG+" method=";

  private MyCombinedChart mCombinedchart;
  private DataParse mData;
  private XAxis xAxisK;
  private YAxis axisLeftK;
  private YAxis axisRightK;
  private float sum = 0;
  private Context mContext;
  //默认显示K线数量
  float showNumber=49;
  DecimalFormat mDecimalFormat;
  private MyCombinedChart mViceChartView;
  private int numberOfKLineDate=0;
  private int numberOfViceDate=0;
  private MyRightMarkerView rightMarkerView;
  private MyRightMarkerView markerView;
  private int nativeKLineType=0;
  MyBottomMarkerView bottomMarkerView;

  private CandleControl(Context context,MyCombinedChart combinedChart,MyCombinedChart viceChart){
    mContext=context;
    mCombinedchart=combinedChart;
    mViceChartView=viceChart;
    initChart(mCombinedchart);
    initChart(mViceChartView);
    setOnChartGestureListener();
    mDecimalFormat=new DecimalFormat("#0.00");
    rightMarkerView = new MyRightMarkerView(mContext, R.layout.mymarkerview,mDecimalFormat);
    markerView = new MyRightMarkerView(mContext, R.layout.mymarkerview,mDecimalFormat);
    bottomMarkerView = new MyBottomMarkerView(mContext, R.layout.mymarkerview);
    mCombinedchart.setMarker(rightMarkerView,bottomMarkerView,markerView);
    mViceChartView.setMarker(rightMarkerView,bottomMarkerView,markerView);
  }

  public static CandleControl Build(Context context,MyCombinedChart combinedChart,MyCombinedChart viceChart){
    return new CandleControl(context,combinedChart,viceChart);
  }

  private void initChart(MyCombinedChart mCombinedchart){

    /****************************************************************/
    mCombinedchart.setDrawBorders(true);
    mCombinedchart.setBorderWidth(0.5F);
    mCombinedchart.setMinOffset(0);
    mCombinedchart.setExtraRightOffset(5f);
    mCombinedchart.setExtraBottomOffset(15f);
    mCombinedchart.setBorderColor(ChartThemeUtil.instance().color_line);
    mCombinedchart.setDescription("");
    mCombinedchart.setDragEnabled(true);
    mCombinedchart.setScaleYEnabled(false);
    mCombinedchart.setAutoScaleMinMaxEnabled(true);
    mCombinedchart.setDoubleTapToZoomEnabled(false);
    mCombinedchart.setPinchZoom(true);
    mCombinedchart.setLogEnabled(false);

    Legend combinedchartLegend = mCombinedchart.getLegend();
    combinedchartLegend.setEnabled(false);
    //bar x y轴
    xAxisK = mCombinedchart.getXAxis();
    xAxisK.setDrawLabels(true);
    xAxisK.setDrawGridLines(true);
    xAxisK.setDrawAxisLine(false);
    xAxisK.setTextColor(Color.argb(0,255,255,255));
    xAxisK.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxisK.setGridColor(ChartThemeUtil.instance().color_line);

    axisLeftK = mCombinedchart.getAxisLeft();
    axisLeftK.setDrawGridLines(false);
    axisLeftK.setDrawAxisLine(false);
    axisLeftK.setDrawLabels(false);
    axisLeftK.setTextColor(Color.RED);
    axisLeftK.setGridColor(ChartThemeUtil.instance().color_line);
    axisLeftK.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);



    axisRightK = mCombinedchart.getAxisRight();
    axisRightK.setDrawGridLines(true);
    axisRightK.setDrawAxisLine(false);
    axisRightK.setDrawLabels(true);
    axisRightK.setTextColor(ChartThemeUtil.instance().color_text);
    axisRightK.setTextSize(11);
    axisRightK.setGridColor(ChartThemeUtil.instance().color_line);
    axisRightK.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
    axisRightK.enableGridDashedLine(3,4,0);
    axisRightK.setLabelCount(7,true);
        /*axisRightK.setSpaceTop(0);
        axisRightK.setSpaceBottom(0)*/;
    YAxisRenderer yAxisRenderer=new GWYAxisRenderer(mCombinedchart.getViewPortHandler(),axisRightK,mCombinedchart.getTransformer(
        YAxis.AxisDependency.RIGHT));
    mCombinedchart.setRendererRightYAxis(yAxisRenderer);


    mCombinedchart.setDragDecelerationEnabled(true);
    mCombinedchart.setDragDecelerationFrictionCoef(0.2f);

  }

  private void setOnChartGestureListener(){
    // 将K线控的滑动事件传递给交易量控件
    mCombinedchart.setOnChartGestureListener(new CoupleChartGestureListener(mCombinedchart, new Chart[]{mViceChartView}));
    // 将交易量控件的滑动事件传递给K线控件

    mCombinedchart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
      @Override
      public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {

        Highlight highlight=new Highlight(h.getXIndex(),Float.MAX_VALUE,h.getDataIndex(),h.getDataSetIndex());
        mViceChartView.highlightValues(new Highlight[]{highlight});
      }

      @Override
      public void onNothingSelected() {
        mViceChartView.highlightValue(null);
        mCombinedchart.onUpdateIndictor(mCombinedchart.getData().getXValCount()+1);
      }
    });

    // 将K线控的滑动事件传递给交易量控件
    mViceChartView.setOnChartGestureListener(new CoupleChartGestureListener(mViceChartView, new Chart[]{mCombinedchart}));
    // 将交易量控件的滑动事件传递给K线控件

    mViceChartView.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
      @Override
      public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        Highlight highlight=new Highlight(h.getXIndex(),Float.MAX_VALUE,h.getDataIndex(),h.getDataSetIndex());
        mCombinedchart.highlightValues(new Highlight[]{highlight});
      }

      @Override
      public void onNothingSelected() {
        if(null!=mCombinedchart.getHighlighted()) {
          mCombinedchart.highlightValue(null);
          mCombinedchart.onUpdateIndictor(mCombinedchart.getData().getXValCount()+1);
        }else {
          mViceChartView.onNextIndictor();
        }
      }
    });


  }


  /**
   * set CandleData in Chart
   * @param mData
   */

  CandleData setCandleChartData(DataParse mData){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
    ArrayList<CandleEntry> candleEntries = new ArrayList<>();
    for (int i = 0, j = 0; i < mData.getkModel().size(); i++, j++) {
      candleEntries.add(new CandleEntry(i, (float) mData.getkModel().get(i).highPrice, (float)mData.getkModel().get(i).lowPrice,(float) mData.getkModel().get(i).openPrice, (float)mData.getkModel().get(i).lastPrice));
    }
    CandleDataSet candleDataSet = new CandleDataSet(candleEntries, "KLine");
    candleDataSet.setDrawHorizontalHighlightIndicator(false);
    candleDataSet.setDrawVerticalHighlightIndicator(false);
    candleDataSet.setHighlightEnabled(false);
    candleDataSet.setHighLightColor(ChartThemeUtil.instance().color_time_line);

    //candleDataSet.setValueTextSize(10f);
    candleDataSet.setDrawValues(false);
    //candleDataSet.setColor(Color.RED);

    candleDataSet.setNeutralColor(ChartThemeUtil.instance().IdleColor);
    candleDataSet.setIncreasingColor(ChartThemeUtil.instance().RiseColor);
    candleDataSet.setDecreasingColor(ChartThemeUtil.instance().FallColor);
    candleDataSet.setShadowWidth(0.5f);
    candleDataSet.setDecreasingPaintStyle(Paint.Style.FILL_AND_STROKE);
    if(GTConfig.instance().getBooleanValue(GTConfig.PREF_HOLLOW_LINE, false)) {
      candleDataSet.setIncreasingPaintStyle(Paint.Style.STROKE);
    }else {
      candleDataSet.setIncreasingPaintStyle(Paint.Style.FILL);
    }
    candleDataSet.setShadowColorSameAsCandle(true);
    candleDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
    return new CandleData(getXVals(mData), candleDataSet);
  }

  /**
   * set CandleData in Chart
   * @param mData
   */

  StickData setStickChartData(DataParse mData){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
    ArrayList<CandleEntry> candleEntries = new ArrayList<>();
    for (int i = 0, j = 0; i < mData.getkModel().size(); i++, j++) {
      candleEntries.add(new CandleEntry(i, (float) mData.getkModel().get(i).highPrice, (float)mData.getkModel().get(i).lowPrice,(float) mData.getkModel().get(i).openPrice, (float)mData.getkModel().get(i).lastPrice));
    }
    CandleDataSet candleDataSet = new CandleDataSet(candleEntries, "KLine");
    candleDataSet.setDrawHorizontalHighlightIndicator(false);
    candleDataSet.setDrawVerticalHighlightIndicator(false);
    candleDataSet.setHighlightEnabled(false);
    candleDataSet.setHighLightColor(ChartThemeUtil.instance().color_chart_cursor);

    //candleDataSet.setValueTextSize(10f);
    candleDataSet.setDrawValues(false);
    //candleDataSet.setColor(Color.RED);
    candleDataSet.setShowCandleBar(false);
    candleDataSet.setNeutralColor(ChartThemeUtil.instance().IdleColor);
    candleDataSet.setIncreasingColor(ChartThemeUtil.instance().RiseColor);
    candleDataSet.setDecreasingColor(ChartThemeUtil.instance().FallColor);
    candleDataSet.setShadowWidth(0.5f);
    candleDataSet.setDecreasingPaintStyle(Paint.Style.FILL_AND_STROKE);
    if(GTConfig.instance().getBooleanValue(GTConfig.PREF_HOLLOW_LINE, false)) {
      candleDataSet.setIncreasingPaintStyle(Paint.Style.STROKE);
    }else {
      candleDataSet.setIncreasingPaintStyle(Paint.Style.FILL);
    }
    candleDataSet.setShadowColorSameAsCandle(true);
    candleDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
    return new StickData(getXVals(mData), candleDataSet);
  }

  ArrayList<String> getXVals(DataParse mData){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
    ArrayList<String> xVals = new ArrayList<>();
    for (int i = 0, j = 0; i < mData.getkModel().size(); i++, j++) {
      if(mData.getNativeKLineType()== Periodicity.K_LINE_TYPE_MONTH){
        xVals.add(StringFormatter.instance().secondToDate2(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()==Periodicity.K_LINE_TYPE_WEEK){
        xVals.add(StringFormatter.instance().secondToDate2(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()==Periodicity.K_LINE_TYPE_DAY){
        xVals.add(StringFormatter.instance().secondToDate2(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()==Periodicity.K_LINE_TYPE_4HOUR){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()==Periodicity.K_LINE_TYPE_2HOUR){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()==Periodicity.K_LINE_TYPE_60MIN){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()==Periodicity.K_LINE_TYPE_30MIN){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()== Periodicity.K_LINE_TYPE_15MIN){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()== Periodicity.K_LINE_TYPE_5MIN){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }else if(mData.getNativeKLineType()== Periodicity.K_LINE_TYPE_1MIN){
        xVals.add(StringFormatter.instance().secondToDate3(mData.getkModel().get(i).priceTime));
      }
    }
    return xVals;
  }


  private LineData setLineChartData(DataParse dataParse,boolean main){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",dataParse="+dataParse+",main="+main);
    List<ILineDataSet> dataSets=new ArrayList<>();
    GTTIndicatorsModel indicators;
    if(main) {
      indicators = dataParse.getmSuperIndicators();
    }else {
      indicators = dataParse.getmViceIndicators();
    }
    for (int n=0;n<indicators.mLineList.size();n++){
      List<Entry>list=new ArrayList<>();
      int number=dataParse.getkModel().size()-indicators.mLineList.get(n).mLineData.mLines.size();
      for (int i=0;i<indicators.mLineList.get(n).mLineData.mLines.size()+number;i++){
        if(i<number)continue;
        double Yval=indicators.mLineList.get(n).mLineData.mLines.get(i-number);
        Entry entry=new Entry((float)Yval,i);
        list.add(entry);
      }
      LineDataSet lineDataSet = new LineDataSet(list,indicators.mLineList.get(n).mName);
      switch (indicators.mLineList.get(n).mType){
        case 0:
          lineDataSet.setMode(LineDataSet.Mode.LINEAR);
          break;
        case 3:
          lineDataSet.setMode(LineDataSet.Mode.CIRCLE);
          break;
        case 6:
          lineDataSet.setMode(LineDataSet.Mode.STICK);
          break;
      }
      lineDataSet.setColor(indicators.mLineList.get(n).mColor);
      lineDataSet.setDrawCircles(false);
      lineDataSet.setDrawValues(false);
      if(n==0) {
        lineDataSet.setDrawHorizontalHighlightIndicator(true);
        lineDataSet.setDrawVerticalHighlightIndicator(true);
        lineDataSet.setHighlightEnabled(true);
      }else {
        lineDataSet.setDrawHorizontalHighlightIndicator(false);
        lineDataSet.setDrawVerticalHighlightIndicator(false);
        lineDataSet.setHighlightEnabled(false);
      }
      lineDataSet.setHighLightColor(ChartThemeUtil.instance().color_chart_cursor);
      lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
      lineDataSet.setLineWidth(0.75f);
      dataSets.add(lineDataSet);
    }
    return new LineData(getXVals(dataParse),dataSets);
  }


  public void setData(DataParse mData,MyCombinedChart myCombinedChart,boolean main) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData+",main="+main);
    if(main&&numberOfKLineDate>=mData.getKLineDatas().size()){
      numberOfKLineDate=0;
    }else if(!main&&numberOfViceDate>=mData.getKLineDatas().size()) {
      numberOfViceDate=0;
    }
    boolean isMin=false;
    if(null!=myCombinedChart.getData()&&myCombinedChart.getData().getXValCount()!=0) {
      /*if(mViceChartView.getVisibility()== View.VISIBLE) {
        showNumber = (float) mViceChartView.getData().getXValCount() / mViceChartView.getScaleX();
      }else {
        showNumber = (float) mCombinedchart.getData().getXValCount() / mCombinedchart.getScaleX();
      }*/
      if(main&&mViceChartView.getVisibility()== View.VISIBLE) {
        showNumber = (float) mViceChartView.getData().getXValCount() / mViceChartView.getScaleX();
      }else if(main&&mViceChartView.getVisibility()!= View.VISIBLE) {
        showNumber = (float) mCombinedchart.getData().getXValCount() / mCombinedchart.getScaleX();
      }
    }else {
      showNumber=49;
    }
    if (mData.getKLineDatas().size() == 0) {
      myCombinedChart.setNoDataText("暂无数据");
      return;
    }
    Logger.e("spenceChart","showNumber="+showNumber);
      this.mData = mData;
    ArrayList<String>xVals=getXVals(mData);

    CombinedData combinedData = new CombinedData(xVals);
    if(main) {
      //设置k线数据
      if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.BAR_CHART){
        combinedData.setData(setStickChartData(mData));
        //设置指标
        combinedData.setData(setLineChartData(mData,main));
        mCombinedchart.getXAxis().setHasHighlightlongTime(false);
      }else if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.CANDLE_STICK){
        combinedData.setData(setCandleChartData(mData));
        //设置指标
        combinedData.setData(setLineChartData(mData,main));
        mCombinedchart.getXAxis().setHasHighlightlongTime(false);
      }else if(ChartConfig.instance().getChartRendererType()== ChartRendererFactory.ChartRendererType.LINE_CHART){
        LineData lineData=setLineChartData(mData,main);
        lineData.getDataSets().addAll(setLineChartData(mData));
        combinedData.setData(lineData);
        mCombinedchart.getXAxis().setHasHighlightlongTime(true);
      }
      myCombinedChart.showNowPrice(GTConfig.instance().getBooleanValue(GTConfig.PREF_NEW_PRICE, false));
      axisRightK.setLabelCount(7,true);
      //myCombinedChart.setHasHighlightlongTime(false);

    }else {
      //设置指标
      combinedData.setData(setLineChartData(mData,main));
      myCombinedChart.setMain(false);
      axisRightK.setLabelCount(3,true);
    }
    final ViewPortHandler viewPortHandlerCombin = myCombinedChart.getViewPortHandler();
    float xscaleCombin = getScaleNomal(xVals.size());
    if(null==mViceChartView.getData()||mViceChartView.getData().getXValCount()>mData.getKLineDatas().size()) {
      viewPortHandlerCombin.setMaximumScaleX(xVals.size()/25f);
      viewPortHandlerCombin.setMinimumScaleX(xVals.size()/187f);
      viewPortHandlerCombin.getMatrixTouch().setScale(xscaleCombin, 1f);
      isMin=true;
    }
    myCombinedChart.setData(combinedData);
    setMarkerView(myCombinedChart);
    if(!isMin) {
      viewPortHandlerCombin.setMaximumScaleX(xVals.size()/25f);
      viewPortHandlerCombin.setMinimumScaleX(xVals.size()/187f);
      viewPortHandlerCombin.getMatrixTouch().setScale(xscaleCombin, 1f);
    }

    if (main) {
        myCombinedChart.moveViewToX( mData.getKLineDatas().size()- numberOfKLineDate - 1);
        numberOfKLineDate = mData.getKLineDatas().size();
      } else {
        myCombinedChart.moveViewToX(mData.getKLineDatas().size() - numberOfViceDate - 1);
        numberOfViceDate = mData.getKLineDatas().size();
      }

  }

  private float getScaleNomal(int size){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",size="+size);
    return (float)size/ showNumber;
  }





  private void setMarkerView(MyCombinedChart myCombinedchart) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
    myCombinedchart.setMarker(rightMarkerView,bottomMarkerView, markerView,myCombinedchart.getData(),mData);
  }

  /*设置量表对齐*/
  private void setOffset() {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
    float lineTop=mCombinedchart.getViewPortHandler().offsetTop();
    float lineRight = mCombinedchart.getViewPortHandler().offsetRight();
    float barRight = mViceChartView.getViewPortHandler().offsetRight();
    float lineBottom = mCombinedchart.getViewPortHandler().offsetBottom();
    float barBottom = mViceChartView.getViewPortHandler().offsetBottom();
    float barTop=mViceChartView.getViewPortHandler().offsetTop();
    float offsetLeft, offsetRight;
    float transLeft = 0, transRight = 0;
  /*注：setExtraRight...函数是针对图表绝对位置计算，比如A表offRightA=20dp,B表offRightB=30dp,则A.setExtraLeftOffset(30),并不是10，还有注意单位转换*/
    if (barRight < lineRight) {
            offsetRight = Utils.convertPixelsToDp(lineRight-barRight);
      mCombinedchart.setExtraRightOffset(offsetRight);
      mCombinedchart.setViewPortOffsets(0, lineTop, lineRight, lineBottom);
      mViceChartView.setViewPortOffsets(0, barTop, lineRight, lineBottom);
      //transRight = lineRight;
    } else if(barRight > lineRight) {
      offsetRight = Utils.convertPixelsToDp(barRight-lineRight);
      mViceChartView.setExtraRightOffset(offsetRight);
      //transRight = barRight;
      mCombinedchart.setViewPortOffsets(0, lineTop, barRight, lineBottom);
      mViceChartView.setViewPortOffsets(0, barTop, barRight, lineBottom);
    }
  }


  @Override
  public void refreshData(DataParse mData) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",mData="+mData);
    mCombinedchart.highlightValue(null);
    mViceChartView.highlightValue(null);
    if(mData.getNativeKLineType()!=nativeKLineType){
      nativeKLineType=mData.getNativeKLineType();
      numberOfKLineDate=0;
      numberOfViceDate=0;
    }
    setData(mData,mCombinedchart,true);
    setOffset();
    setData(mData,mViceChartView,false);
    setOffset();
  }

  @Override
  public void addMaxMinValue() {

  }

  @Override
  public void addDataToFoot(KLineBean kLineBean,GTTIndicatorsModel mainIndicatorsModel,GTTIndicatorsModel secondIndicatorsModel) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",kLineBean="+kLineBean+",mainIndicatorsModel="+mainIndicatorsModel+",secondIndicatorsModel="+secondIndicatorsModel);
    //KLineBean newKLineBean=kLineBean;
    mCombinedchart.addEntryToMinuteHelper(kLineBean);
    kLineBean.date=changeType(Long.parseLong(kLineBean.date));
    CombinedData combinedData=mCombinedchart.getData();
    combinedData.addXValue(kLineBean.date);
    if(null!=combinedData.getCandleData()){
      CandleData candleData=combinedData.getCandleData();
      candleData.addXValue(kLineBean.date);
      int dayNumber=candleData.getXVals().size()-1;
      CandleEntry candleEntry=new CandleEntry(dayNumber,kLineBean.high,kLineBean.low,kLineBean.open,kLineBean.close);
      candleData.getDataSets().get(0).addEntry(candleEntry);
    }else if(null!=combinedData.getStickData()){
      StickData stickData=combinedData.getStickData();
      stickData.addXValue(kLineBean.date);
      int dayNumber=stickData.getXVals().size()-1;
      CandleEntry candleEntry=new CandleEntry(dayNumber,kLineBean.high,kLineBean.low,kLineBean.open,kLineBean.close);
      stickData.getDataSets().get(0).addEntry(candleEntry);
    }else {
      LineData lineData=combinedData.getLineData();
      lineData.addXValue(kLineBean.date);
      int dayNumber=lineData.getXVals().size()-1;
      Entry entry=new Entry(kLineBean.close,dayNumber);
      lineData.getDataSetByLabel("KLine",true).addEntry(entry);
    }

    LineData lineData=combinedData.getLineData();
    lineData.addXValue(kLineBean.date);
    for(GTTLineModel gttLineModel:mainIndicatorsModel.mLineList){
      String name=gttLineModel.mName;
      int dayNumber=lineData.getXVals().size()-1;
      int indexLast=gttLineModel.mLineData.mLines.size()-1;
      //如果指标数组异常，则跳过
      if(indexLast==-1)continue;
      double Yval=gttLineModel.mLineData.mLines.get(indexLast);
      Entry entry=new Entry((float) Yval,dayNumber);
      lineData.getDataSetByLabel(name,true).addEntry(entry);
    }

    mCombinedchart.notifyDataSetChanged();
    mCombinedchart.invalidate();


    /**
     * 副图指标更新
     */
    CombinedData viceCombinedData=mViceChartView.getData();
    viceCombinedData.addXValue(kLineBean.date);
    LineData viceLineData=viceCombinedData.getLineData();
    viceLineData.addXValue(kLineBean.date);
    for(GTTLineModel gttLineModel:secondIndicatorsModel.mLineList){
      String name=gttLineModel.mName;
      int dayNumber=viceLineData.getXVals().size()-1;
      int indexLast=gttLineModel.mLineData.mLines.size()-1;
      double Yval=gttLineModel.mLineData.mLines.get(indexLast);
      Entry entry=new Entry((float) Yval,dayNumber);
      viceLineData.getDataSetByLabel(name,true).addEntry(entry);
    }

    mViceChartView.notifyDataSetChanged();
    mViceChartView.invalidate();

  }

  @Override
  public void refreshFootData(KLineBean kLineBean,GTTIndicatorsModel mainIndicatorsModel,GTTIndicatorsModel secondIndicatorsModel) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",kLineBean="+kLineBean);
    changeData(kLineBean,mainIndicatorsModel,secondIndicatorsModel);
    mCombinedchart.refrashEntryToMinuteHelper(kLineBean);
    //mCombinedchart.notifyDataSetChanged();
    //mCombinedchart.invalidate();
  }

  private void changeData(KLineBean kLineBean,GTTIndicatorsModel mainIndicatorsModel,GTTIndicatorsModel secondIndicatorsModel){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",kLineBean="+kLineBean);
    CombinedData combinedData=mCombinedchart.getData();
    if(null!=combinedData.getCandleData()){
      CandleData candleData=combinedData.getCandleData();
      int dayNumber=candleData.getXVals().size()-1;
      CandleEntry candleEntry=new CandleEntry(dayNumber,kLineBean.high,kLineBean.low,kLineBean.open,kLineBean.close);
      candleData.getDataSets().get(0).removeLast();
      candleData.getDataSets().get(0).addEntry(candleEntry);
    }else if(null!=combinedData.getStickData()){
      StickData stickData=combinedData.getStickData();
      int dayNumber=stickData.getXVals().size()-1;
      CandleEntry candleEntry=new CandleEntry(dayNumber,kLineBean.high,kLineBean.low,kLineBean.open,kLineBean.close);
      stickData.getDataSets().get(0).removeLast();
      stickData.getDataSets().get(0).addEntry(candleEntry);
    }else{
      LineData lineData=combinedData.getLineData();
      int dayNumber=lineData.getXVals().size()-1;
      Entry entry=new Entry(kLineBean.close,dayNumber);
      lineData.getDataSetByLabel("KLine",true).removeLast();
      lineData.getDataSetByLabel("KLine",true).addEntry(entry);
    }
    /**
     * 主图指标更新
     */
    LineData lineData=combinedData.getLineData();
    int n=0;
    for(GTTLineModel gttLineModel:mainIndicatorsModel.mLineList){
      String name=gttLineModel.mName;
      lineData.getDataSetByLabel(name,true).clear();
      int number=combinedData.getXValCount()-gttLineModel.mLineData.mLines.size();
      for (int i=0;i<gttLineModel.mLineData.mLines.size()+number;i++){
        if(i<number)continue;
        double value=gttLineModel.mLineData.mLines.get(i-number);
        Entry entry=new Entry((float) value,i);
        lineData.getDataSetByLabel(name,true).addEntry(entry);

      }
      n=n+1;
    }

    //mCombinedchart.notifyDataSetChanged();
    //mCombinedchart.invalidate();

    /**
     * 副图指标更新
     */
    CombinedData viceCombinedData=mViceChartView.getData();
    LineData viceLineData=viceCombinedData.getLineData();
    int i=0;
    for(GTTLineModel gttLineModel:secondIndicatorsModel.mLineList){
      String name=gttLineModel.mName;
      viceLineData.getDataSetByLabel(name,true).clear();
      int number=viceCombinedData.getXValCount()-gttLineModel.mLineData.mLines.size();
      for (int k=0;k<gttLineModel.mLineData.mLines.size()+number;k++){
        if(k<number)continue;
        double value=gttLineModel.mLineData.mLines.get(k-number);
        Entry entry=new Entry((float) value,k);
        viceLineData.getDataSetByLabel(name,true).addEntry(entry);
      }
      i=i+1;
    }

    //mViceChartView.notifyDataSetChanged();
    //mViceChartView.invalidate();
  }

  @Override
  public void setProductDecimalNum(int num) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",num="+num);
    refreshProductDecimalNum(num);
    mCombinedchart.getAxisRight().setValueFormatter(new YAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, YAxis yAxis) {
          return mDecimalFormat.format(value);
        }
      });
    mViceChartView.getAxisRight().setValueFormatter(new YAxisValueFormatter() {
      @Override
      public String getFormattedValue(float value, YAxis yAxis) {
        return mDecimalFormat.format(value);
      }
    });
    //numberOfKLineDate=0;
    //numberOfViceDate=0;
  }
  private void DecimalFormat(int num){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",num="+num);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < num; i++) {
      sb.append(String.valueOf("0"));
    }
    if(num==0){
      mDecimalFormat = new DecimalFormat("#0");
    }else {
      mDecimalFormat = new DecimalFormat("#0"+"."+sb.toString());
    }
  }

  @Override public void refreshData(GTTIndicatorsModel indicatorsModel, boolean main) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",indicatorsModel="+indicatorsModel+",main="+main);
    GTTIndicatorsModel gttIndicatorsModel=indicatorsModel;
    if(null==gttIndicatorsModel||null==mData)return;
      if (main) {
        mData.setmSuperIndicators(gttIndicatorsModel);
        refreshIndicators(mCombinedchart, true);
      } else {
        mData.setmViceIndicators(gttIndicatorsModel);
        refreshIndicators(mViceChartView, false);
      }
  }
  private void refreshIndicators(MyCombinedChart myCombinedChart,boolean main){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",myCombinedChart="+myCombinedChart+",main="+main);
    ArrayList<String>xVals=getXVals(mData);
    CombinedData combinedData = new CombinedData(xVals);
    if(main){
      //设置k线数据
      if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.BAR_CHART){
        combinedData.setData(setStickChartData(mData));
        combinedData.setData(setLineChartData(mData,main));
      }else if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.CANDLE_STICK){
        combinedData.setData(setCandleChartData(mData));
        combinedData.setData(setLineChartData(mData,main));
      }else if(ChartConfig.instance().getChartRendererType()== ChartRendererFactory.ChartRendererType.LINE_CHART){
        LineData lineData=setLineChartData(mData,true);
        lineData.getDataSets().addAll(setLineChartData(mData));
        combinedData.setData(lineData);
      }
      myCombinedChart.setData(combinedData);
    }else {
      combinedData.setData(setLineChartData(mData,main));
      myCombinedChart.setData(combinedData);
    }
  }

  /**
   * 刷新阳线类型
   *
   */
  public void refreshCandleData(){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName());
    if(null==mData)return;
    ArrayList<String>xVals=getXVals(mData);
    CombinedData combinedData = new CombinedData(xVals);
      //设置k线数据
    if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.BAR_CHART){
      combinedData.setData(setStickChartData(mData));
      //设置指标
      combinedData.setData(setLineChartData(mData,true));
      mCombinedchart.getXAxis().setHasHighlightlongTime(false);
    }else if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.CANDLE_STICK){
      combinedData.setData(setCandleChartData(mData));
      //设置指标
      combinedData.setData(setLineChartData(mData,true));
      mCombinedchart.getXAxis().setHasHighlightlongTime(false);
    }else if(ChartConfig.instance().getChartRendererType()==ChartRendererFactory.ChartRendererType.LINE_CHART){
      LineData lineData=setLineChartData(mData,true);
      lineData.getDataSets().addAll(setLineChartData(mData));
      combinedData.setData(lineData);
      mCombinedchart.getXAxis().setHasHighlightlongTime(true);
    }
    mCombinedchart.setData(combinedData);
    mCombinedchart.notifyDataSetChanged();
    mCombinedchart.invalidate();
  }

  private List<ILineDataSet> setLineChartData(DataParse dataParse){
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",dataParse="+dataParse);
    List<ILineDataSet> dataSets=new ArrayList<>();
    List<Entry>list=new ArrayList<>();
    for (int n = 0, j = 0; n < mData.getkModel().size(); n++, j++) {
      double Yval = mData.getkModel().get(n).lastPrice;
      Entry entry = new Entry((float) Yval, n);
      list.add(entry);
    }
      LineDataSet lineDataSet = new LineDataSet(list,"KLine");
      lineDataSet.setMode(LineDataSet.Mode.LINEAR);
      lineDataSet.setColor(Color.BLACK);
      lineDataSet.setDrawCircles(false);
      lineDataSet.setDrawValues(false);
      lineDataSet.setDrawHorizontalHighlightIndicator(false);
      lineDataSet.setDrawVerticalHighlightIndicator(false);
      lineDataSet.setHighlightEnabled(false);
      lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
      lineDataSet.setLineWidth(0.75f);
      dataSets.add(lineDataSet);

    return dataSets;
  }

  @Override public void setStartTime(int startTime) {

  }

  @Override public void refreshProductDecimalNum(int num) {
    Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",num="+num);
    DecimalFormat(num);
    mCombinedchart.getAxisRight().setValueFormatter(new YAxisValueFormatter() {
      @Override
      public String getFormattedValue(float value, YAxis yAxis) {
        return mDecimalFormat.format(value);
      }
    });
    mViceChartView.getAxisRight().setValueFormatter(new YAxisValueFormatter() {
      @Override
      public String getFormattedValue(float value, YAxis yAxis) {
        return mDecimalFormat.format(value);
      }
    });
    mCombinedchart.refreshProductDecimalNum(mDecimalFormat);
    mViceChartView.refreshProductDecimalNum(mDecimalFormat);
  }

  /**
   * 根据类型输出日期格式
   * @param time
   * @return
   */
  private  String changeType(long time){
    if(nativeKLineType== Periodicity.K_LINE_TYPE_MONTH){
      return changeTimeToYYYYMMDD(time);
    }else if(nativeKLineType==Periodicity.K_LINE_TYPE_WEEK){
      return changeTimeToYYYYMMDD(time);
    }else if(nativeKLineType==Periodicity.K_LINE_TYPE_DAY){
      return changeTimeToYYYYMMDD(time);
    }else if(nativeKLineType==Periodicity.K_LINE_TYPE_4HOUR){
      return changeTimeToMMDDhhmm(time);
    }else if(nativeKLineType==Periodicity.K_LINE_TYPE_2HOUR){
      return changeTimeToMMDDhhmm(time);
    }else if(nativeKLineType==Periodicity.K_LINE_TYPE_60MIN){
      return changeTimeToMMDDhhmm(time);
    }else if(nativeKLineType==Periodicity.K_LINE_TYPE_30MIN){
      return changeTimeToMMDDhhmm(time);
    }else if(nativeKLineType== Periodicity.K_LINE_TYPE_15MIN){
      return changeTimeToMMDDhhmm(time);
    }else if(nativeKLineType== Periodicity.K_LINE_TYPE_5MIN){
      return changeTimeToMMDDhhmm(time);
    }else if(nativeKLineType== Periodicity.K_LINE_TYPE_1MIN){
      return changeTimeToMMDDhhmm(time);
    }else
      return null;
  }

  private String changeTimeToYYYYMMDD(long time){
    Date date=new Date(time*1000);
    return new SimpleDateFormat("yyyy/MM/dd").format(date);
  }

  private String changeTimeToMMDDhhmm(long time){
    Date date=new Date(time*1000);
    return new SimpleDateFormat("yyyy/MM/dd HH:mm").format(date);
  }

}
